﻿(function () {

    layui.use(["layer", "jquery", "table", "form", "laydate"], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form;
        var laydate = layui.laydate;
        var userls = [];
        var buyerUserId = 0;
        var sellerUserId = 0;
        var premiumOrderArr = [];   // 溢价订单表

        $(document).ready(function () {
            userls = JSON.parse($("#hdUserListJson").val());
            //console.log(arr);

            $(document).bind("keydown", onDocumentKeyDown)
            $("#btnAddOrder").bind("click", onAddOrderBtnClick);

            $("#txtSearchSeller").bind("input propertychange", onSellerInputChange);
            $("#txtSearchBuyer").bind("input propertychange", onBuyerInputChange);

            initUserList();

            $("#btnSetAutoOrderAmount").click(onSetAutoOrderAmountBtnClick);
            $("#btnViewAutoOrderAmount").click(onViewAutoOrderAmountBtnClick);
        });

        function initUserList() {
            var html = '';
            userls.forEach(item => {
                var prop = 'tagUserId="' + item["Id"] + '" ';
                prop += 'tagName="' + item["Name"] + '" ';
                prop += 'tagPhone="' + item["Phone"] + '" ';
                var title = item["Phone"];
                html += '<label ' + prop + ' title="' + title + '" class="container-list-item">' + item["Name"] + '</label>';
            });
            $("#SellerList").append(html);
            $("#SellerList label").bind("click", onSellerItemClick);
            $("#SellerList label").hover(function () {
                $(this).addClass("container-list-item-highlight");
            }, function () {
                $(this).removeClass("container-list-item-highlight");
            });

            $("#BuyerList").append(html);
            $("#BuyerList label").bind("click", onBuyerItemClick);
            $("#BuyerList label").hover(function () {
                $(this).addClass("container-list-item-highlight");
            }, function () {
                $(this).removeClass("container-list-item-highlight");
            });
        }

        function onSellerInputChange() {
            var val = $("#txtSearchSeller").val();
            var els = $("#SellerList label");
            for (var i = 0; i < els.length; i++) {
                var item = els.eq(i);
                if (item.text().indexOf(val) > -1) {
                    item.show();
                } else {
                    item.hide();
                }
            }
        }

        function onSellerItemClick(el) {
            $("#lbSeller").text($(this).text());
            sellerUserId = $(this).attr("tagUserId");
            $("#txtAmount").val("");
            for (var i = 0; i < premiumOrderArr.length; i++) {
                var item = premiumOrderArr[i];
                if (item["BuyUserId"] == sellerUserId) {
                    $("#txtAmount").val(item["Amount"].toFixed(2));
                    break;
                }
            }
        }

        function onBuyerInputChange() {
            var val = $("#txtSearchBuyer").val();
            var els = $("#BuyerList label");
            for (var i = 0; i < els.length; i++) {
                var item = els.eq(i);
                if (item.text().indexOf(val) > -1) {
                    item.show();
                } else {
                    item.hide();
                }
            }
        }

        function onBuyerItemClick(el) {
            $("#lbBuyer").text($(this).text());
            buyerUserId = $(this).attr("tagUserId");
        }

        function onDocumentKeyDown(e) {
            if (e.which == 13) {
                submitAddOrder();
            }
        }

        function onAddOrderBtnClick() {
            submitAddOrder();
        }

        function submitAddOrder() {
            if (validateForm()) {
                var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                    { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                $.ajax("/Order/CreateOrder", {
                    method: "POST",
                    data: {
                        BuyerUserId: buyerUserId,
                        SellerUserId: sellerUserId,
                        Amount: $("#txtAmount").val()
                    },
                    complete: function (jqXHR, textStatus) {
                        layer.close(loadingIndex);
                    },
                    success: function (data, textStatus, jqXHR) {
                        $("#txtSearchSeller").focus();
                        if (data.Success == true) {
                            layer.msg(addStyle("创建订单成功！"));
                            buyerUserId = sellerUserId;
                            sellerUserId = 0;
                            $("#lbBuyer").text($("#lbSeller").text());
                            $("#lbSeller").text("请选择！");
                            $("#txtAmount").val("");
                        } else {
                            layer.msg(addStyle("创建订单失败: " + data.Msg));
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg(addStyle("系统错误，请联系管理员！"),
                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                    }
                });
            }
        }

        function validateForm() {
            if (buyerUserId == 0) {
                layer.msg(addStyle("请选择买家！"));
                return false;
            }
            else if (sellerUserId == 0) {
                layer.msg(addStyle("请选择卖家！"));
                return false;
            }
            else if (buyerUserId == sellerUserId) {
                layer.msg(addStyle("买家和卖家不可以是一家！"));
                return false;
            }
            var val = $("#txtAmount").val();
            if (!(val >= 1000 && val <= 15000)) {
                layer.msg(addStyle("订单金额在1000 - 15000之间！"));
                return false;
            }

            return true;
        }

        var _layerId = 0;
        function onSetAutoOrderAmountBtnClick() {
            _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                resize: false,
                content: '<div id="AutoOrderAmountDlg2">' + $("#AutoOrderAmountDlg").html() + '</div>'
            });

            laydate.render({
                elem: '#txtSearchDate',
                value: (new Date()),
                isInitValue: true,
                showBottom: false
            });

            $("#btnSetAutoOrderAmountOK").click(onSetAutoOrderAmountOKBtnClick);
        }

        function onViewAutoOrderAmountBtnClick() {
            handleData(premiumOrderArr);
        }

        function onSetAutoOrderAmountOKBtnClick() {
            layer.confirm("确定要加载订单溢价表吗？",
                { icon: 3, title: "满堂创品", offset: "20%" },
                function () {
                    layer.close(_layerId);
                    var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                        { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                    $.ajax("/Order/QueryPremiumOrder", {
                        method: "POST",
                        data: "date=" + $("#txtSearchDate").val(),
                        complete: function (jqXHR, textStatus) {
                            layer.close(loadingIndex);
                        },
                        success: function (data, textStatus, jqXHR) {
                            if (data.Success == true) {
                                layer.msg(addStyle("获取订单溢价表成功！"));
                                premiumOrderArr = data.Data;
                                handleData(data.Data);
                            } else {
                                layer.msg(addStyle("获取订单溢价表失败！"));
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.msg(addStyle("系统错误，请联系管理员！"),
                                { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                        }
                    });
                }
            );
        }

        function handleData(data) {
            layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                area: ["90%", "95%"],
                resize: false,
                content: '<div id="PremiumOrderDlg2">' + $("#PremiumOrderDlg").html() + '</div>',
                btn: ["确 定"]
            });

            var el = $("#PremiumOrderDlg2 .premiumOrderDlgList > ul").eq(0);
            var html = '';
            data.forEach(item => {
                html += '<li tagUserId="' + item["BuyUserId"] + '">' + item["BuyerName"] + ': ' + item["Amount"].toFixed(2) + '</li>';
            });
            el.append(html);
        }

        function addStyle(str) {
            return '<span style="font-size: 16px;">' + str + '</span>';
        }
    });

})();